package cn.pku.sirx.snad.ads.util;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import cn.pku.sirx.snad.ad.Constants;
import cn.pku.sirx.snad.ad.model.AdDescription;
import cn.pku.sirx.snad.ad.model.UserContext;
import cn.pku.sirx.snad.ad.model.entity.AdContent;
import cn.pku.sirx.snad.ad.util.UserContextStringUtils;

/**
 * @author WangXiao
 */
public abstract class AdDescriptionUtils {

	/**
	 * Convert a list of ad contents to ad descriptions.
	 * 
	 * @param adContents
	 *            ad contents
	 * @param userContext
	 *            user context
	 * @return ad descriptions
	 */
	public static List<AdDescription> toAdDescription(
			List<AdContent> adContents, UserContext userContext) {
		if (adContents == null) {
			return null;
		}

		List<AdDescription> result = new ArrayList<AdDescription>(adContents
				.size());
		for (AdContent adContent : adContents) {
			result.add(toAdDescription(adContent, userContext));
		}
		return result;
	}

	/**
	 * Convert an ad content to ad description.
	 * 
	 * @param adContent
	 *            ad content
	 * @param userContext
	 *            user context
	 * @return ad description
	 */
	public static AdDescription toAdDescription(AdContent adContent,
			UserContext userContext) {
		if (adContent == null) {
			return null;
		}
		AdDescription result = new AdDescription();
		result.setTitle(adContent.getTitle());
		result.setDescription1(adContent.getDesc1());
		result.setDescription2(adContent.getDesc2());
		result.setUrl(adContent.getImpressionLink());
		try {
			result.setLandingPageUrl(String.format("%s?%s=%d&%s=%s&%s=%s",
					CLICK_LOG_URL, Constants.WEB_P_AD_ID, adContent
							.getAdContentId() == null ? 0 : adContent
							.getAdContentId(), Constants.WEB_P_USER_CONTEXT,
					UserContextStringUtils.toUserContextString(userContext),
					Constants.WEB_P_LANDING_PAGE_URL, URLEncoder.encode(
							adContent.getDestLink(), "UTF-8")));
		} catch (UnsupportedEncodingException e) {
			LOG.error(e);
		}
		return result;
	}

	private static final String CLICK_LOG_URL = "http://localhost:8080/ad-click-log-system/log.s";

	private static final Log LOG = LogFactory.getLog(AdDescriptionUtils.class);
}
